﻿using IdentityModel.Client;
using QRCoder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DeviceClientOne
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }



        /// <summary>
        /// 请求api资源
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task CallApiAsync(string token)
        {
            // call api
            var apiClient = new HttpClient();
            apiClient.SetBearerToken(token);
            var response = await apiClient.GetAsync("http://localhost:6001/api/myidentity");
            if (!response.IsSuccessStatusCode)
            {
                var msg = response.Content.ReadAsStringAsync().Result;
                this.pictureBox1.Visible = false;   //隐藏二维码
                this.label2.Text = msg;  //显示返回结果
                //MessageBox.Show($"api返回值为:{msg}");
            }
            else
            {
                var msg = response.Content.ReadAsStringAsync().Result;
                this.pictureBox1.Visible = false;   //隐藏二维码
                this.label2.Text = msg;   //显示返回结果
                //MessageBox.Show($"api返回值为:{msg}");
            }
        }



        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="verificationUriComplete"></param>
        public void CreateQrCode(string verificationUriComplete)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(verificationUriComplete, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(6);
            this.pictureBox1.Image = Image.FromHbitmap(qrCodeImage.GetHbitmap());
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001");    //IDS4服务器
            var deviceResponse = await client.RequestDeviceAuthorizationAsync(new DeviceAuthorizationRequest
            {
                Address = disco.DeviceAuthorizationEndpoint,
                ClientId = "deviceclientone",
                ClientSecret = "12345"
            });
            //生成二维码
            CreateQrCode(deviceResponse.VerificationUriComplete);
            //通过浏览器打开地址
            Process.Start(new ProcessStartInfo(deviceResponse.VerificationUriComplete) { UseShellExecute = true });
            //轮询请求
            string accessToken;
            while (true)
            {
                // request token
                var tokenResponse = await client.RequestDeviceTokenAsync(new DeviceTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "deviceclientone",
                    ClientSecret = "12345",
                    DeviceCode = deviceResponse.DeviceCode
                });
                if (!tokenResponse.IsError)
                {
                    accessToken = tokenResponse.AccessToken;
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(deviceResponse.Interval));
                //await Task.Delay(TimeSpan.FromSeconds());
            }
            await CallApiAsync(accessToken);
        }
    }
}
